let fs = require("fs")
let pathApi = require("path")
let iconv = require('iconv-lite');

let CNs = {}

// 获取中文目录
let CNPaths = ["../Languages/CNs"]   
CNPaths.forEach(path => {
    let dirs = fs.readdirSync(path)
    dirs.forEach(file => {
        if(/\.xml$/.test(file)){
            let buffer = fs.readFileSync(path + "/" + file);
            let text = iconv.decode(buffer,"utf-16");
            let ret = text;
            if(ret) {
                ret = ret.match(/<string id=".+" text="[^"]+"\/>/g);
                ret.forEach( v => {
                    if(/<string id="(.+)" text="([^"]+)"\/>/.test(v)){
                        CNs[RegExp.$1] = RegExp.$2
                    }
                })
            }
        }
    })
    
})


// items文件
let items = {}
let itemPaths = ["../items"]
itemPaths.forEach(dir => {
    let dirs = fs.readdirSync(dir)
    dirs.forEach(path => { 
        path = dir + "/" + path;
        let ret = fs.readFileSync(path).toString()
        let arr = ret.match(/id="[^"]+"\n?\s+name="{=[^}]+}/g)
        arr.forEach(function(item){
            if(/id="(.+)"\n?\s+name="{=(.+)}$/.test(item)){
                items[`"${RegExp.$1}"`] = `"${CNs[RegExp.$2]}"`
                items[`"Item.${RegExp.$1}"`] = `"${CNs[RegExp.$2]}"`
                ret = ret.replace(new RegExp(`"${RegExp.$1}"`,"ig"), `"${CNs[RegExp.$2]}"`)
            }
        })
        if(!fs.existsSync(pathApi.dirname(path) + "cn")){
            fs.mkdirSync(pathApi.dirname(path) + "cn")
        }
        fs.writeFile(pathApi.dirname(path) + "cn/" + pathApi.basename(path), ret, function(err) {
            if(err) {
                return;
            }
        });
    })
})

// 人物
let charactersPath = ["../spnpccharacters.xml"];
charactersPath.forEach(path => {
    let ret = fs.readFileSync(path).toString()
    for (let key in CNs) {
        ret = ret.replace(new RegExp( `{=${key}}`,"ig"), CNs[key])
    }
    for (let key in items) {
        ret = ret.replace(new RegExp( key,"ig"), items[key])
    }
    if(!fs.existsSync(pathApi.dirname(path) + "/characterCn")){
        fs.mkdirSync(pathApi.dirname(path) + "/characterCn")
    }
    fs.writeFile(pathApi.dirname(path) + "/characterCn/" + pathApi.basename(path), ret, function(err) {
        if(err) {
            return;
        }
    }); 
})



